/*
 *  Copyright 2012 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.pc.ui.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * The uniques of this class is that for some defined set of properties can't
 * be empty value. If they value is empty will returned null. For registration
 * such property use method {@link #addNullableProperty(String)}.
 *
 * Also, this class is singleton and for getting it instance use method
 * {@link #getInstance()}
 *
 * The main purpose of this class was storing 'hibernate' properties and
 * defining them before spring content had been started up.
 *
 * @author Yuriy Dunko
 */
public class NullableProperties extends Properties {

	private static final long serialVersionUID = 6126503794120027549L;
	
	private static final NullableProperties instance = new NullableProperties();

    public static NullableProperties getInstance(){
        return instance;
    }

    private Set<String> nullablePropertyNames = new HashSet<String>();

    private NullableProperties(){
    }

    public void addNullableProperty(String name){
        nullablePropertyNames.add(name);
    }

    @Override
    @Deprecated
    public String getProperty(String key) {
        String property = super.getProperty(key);
        if (property != null && nullablePropertyNames.contains(property)
                && property.isEmpty()){
            return null;
        }
        return property;
    }


    public void store() {
        try {
            store(new FileOutputStream(
                    ConfigPath.getInstance().getConnectionProp()),
                    "Connection properties");
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    public void load() {
        try {
            load(new FileInputStream(ConfigPath.getInstance().getConnectionProp()));
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}
